package com.openlab.service.basic.epidemic.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.openlab.common.dto.UserTokenDto;
import com.openlab.common.utils.Result;
import com.openlab.common.utils.ResultCode;
import com.openlab.common.utils.TokenManager;
import com.openlab.service.basic.epidemic.dto.*;
import com.openlab.service.basic.epidemic.entity.Epidemic;
import com.openlab.service.basic.epidemic.entity.UserBuilding;
import com.openlab.service.basic.epidemic.service.EpidemicService;
import com.openlab.service.basic.epidemic.service.UserBuildingService;
import com.openlab.service.basic.epidemic.service.WechatMpUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/epidemic")
public class EpidemicController {

    @Autowired
    private EpidemicService epidemicService;

    @Autowired
    private WechatMpUserService wechatMpUserService;

    @Autowired
    private UserBuildingService userBuildingService;

    /**
     * 分页查询
     */
    @PostMapping("/list")
    public Result list(@RequestBody ListRequestParam requestParam){
        // 拿到前端发送的信息
        Integer page_num = requestParam.getPage_num();
        Integer page_size = requestParam.getPage_size();
        Integer community_id = requestParam.getCommunity_id();
        Integer tour_code = requestParam.getTour_code();
        Integer return_hometown = requestParam.getReturn_hometown();
        // 构建分页构造器
        IPage<ListInfo> page = new Page<>(page_num,page_size);
        // 分页查询
        IPage<ListInfo> listInfoIPage = epidemicService.selectPageVo(page,community_id,tour_code,return_hometown);

        // 创建返回给前端的信息
        HashMap<String,Object> data = new HashMap<>();
        data.put("list",listInfoIPage.getRecords());
        data.put("page_num",page_num);
        data.put("page_size",page_size);
        data.put("total",page.getTotal());
        data.put("page_amount",page.getPages());
        return Result.ok(200,data);
    }

    /**
     * 查看详情
     */
    @PostMapping("/detail")
    public Result detail(@RequestBody Map<String,Object> map) {
        // 拿到前端发送回来的信息
        String id = (String) map.get("id");
        Integer community_id = (Integer) map.get("community_id");
        // 查询防控记录详情信息
        DetailDto detail = epidemicService.selectDetail(Long.valueOf(id), community_id);
        // 如果查询到的对象为空，那么返回错误信息
        if (ObjectUtils.isEmpty(detail)) {
            return Result.ok(ResultCode.QUERY_ILLEFAL,"非法查询疫情防控数据");
        }
        // 如果查询的对象不为空，返回给前端
        HashMap<String,Object> data = new HashMap<>();
        data.put("info",detail);
        return Result.ok(ResultCode.SUCCESS,data);
    }

    /**
     * 防控登记
     */
    @PostMapping("/create")
    public Result createEpidemicRecord(@RequestBody CreateRequestParam requestParam, HttpServletRequest request) {
        Long wechatUserId = requestParam.getWechat_mp_user_id();
        Long building_id = requestParam.getBuilding_id();
        Long community_id = requestParam.getCommunity_id();
        // 根据微信id和社区id和buildingid查询 用户名下的房产信息
        List<UserBuilding> buildingList = userBuildingService.selectUserBuilding(wechatUserId, building_id, community_id);
        // 根据登录的token获取到当前登录管理员的id和name
        UserTokenDto userTokenDto = TokenManager.getNameByJwtToken(request);
        // 如果查询到用户名下的房产信息为空，就返回错误状态码
        if (ObjectUtils.isEmpty(buildingList)) {
            return Result.ok(ResultCode.QUERY_ILLEFAL,"非法数据，不能作为疫情防控数据");
        } else {
            // 如果查询到的数据不为空，就将数据存到数据库
            Epidemic epidemic = Epidemic.builder()
                    .wechat_mp_user_id(wechatUserId)
                    .community_id(community_id)
                    .building_id(requestParam.getBuilding_id())
                    .tour_code(requestParam.getTour_code())
                    .return_hometown(requestParam.getReturn_hometown())
                    .temperature(requestParam.getTemperature())
                    .return_from_province(requestParam.getReturn_from_province())
                    .return_from_city(requestParam.getReturn_from_city())
                    .return_from_district(requestParam.getReturn_from_district())
                    .created_by(Long.valueOf(userTokenDto.getId()))
                    .created_at(new Date().getTime())
                    .build();
            epidemicService.save(epidemic);
        }
        HashMap<String,Object> data = new HashMap<>();
        data.put("id",epidemicService.findId());
        return Result.ok(ResultCode.SUCCESS,data);
    }


    /**
     * 根据手机号查找业主
     */
    @PostMapping("/ower")
    public Result findOwer(@RequestBody HashMap<String,Object> map) {
        String phone = (String) map.get("phone");
        Integer community_id = (Integer) map.get("community_id");
        // 通过电话号码查询绑定的微信用户信息
        WechatMpUserDto wechatMpUserDto = wechatMpUserService.findOwer(phone);
        // 如果没有查到说明未注册
        if(ObjectUtils.isEmpty(wechatMpUserDto)) {
            return Result.ok(ResultCode.QUERY_ILLEFAL,"未查询到业主信息");
        }
        // 如果查到，就再根据微信id和社区id查询用户房产信息
        List<UserBuildingDto> buildingList = userBuildingService.findBuilding(wechatMpUserDto.getId(),community_id);
        if (buildingList.isEmpty()){
            return Result.ok(ResultCode.QUERY_ILLEFAL,"未查询到业主信息");
        }

        List<UserBuildingDto> houses = new ArrayList<>();
        List<UserBuildingDto> carports = new ArrayList<>();
        List<UserBuildingDto> warehouses = new ArrayList<>();
        List<UserBuildingDto> merchants = new ArrayList<>();
        List<UserBuildingDto> garages = new ArrayList<>();
        // 遍历房产信息，如果有符合条件的就加入链表中
        for (UserBuildingDto userBuildingDto:buildingList) {
            if (userBuildingDto.getType().equals(Building.HOUSE)){
                houses.add(userBuildingDto);
            }
            if (userBuildingDto.getType().equals(Building.CARPORT)){
                carports.add(userBuildingDto);
            }
            if (userBuildingDto.getType().equals(Building.WAREHOUSE)){
                warehouses.add(userBuildingDto);
            }
            if (userBuildingDto.getType().equals(Building.MERCHANT)){
                merchants.add(userBuildingDto);
            }
            if (userBuildingDto.getType().equals(Building.GARAGE)){
                garages.add(userBuildingDto);
            }
        }
        // 创建返回给前端的信息
        OwerInfo owerInfo = OwerInfo.builder()
                .id(wechatMpUserDto.getId())
                .real_name(wechatMpUserDto.getReal_name())
                .phone(wechatMpUserDto.getPhone())
                .avatar_url(wechatMpUserDto.getAvatar_url())
                .houses(houses)
                .carports(carports)
                .warehouses(warehouses)
                .merchants(merchants)
                .garages(garages)
                .build();
        HashMap<String,Object> data = new HashMap<>();
        data.put("owerInfo",owerInfo);
        return Result.ok(200,data);
    }
}
